import axios from "axios";

export default {
    namespaced: true,
    //写成函数，保证数据独立性
    state() {
        return {
            list: []
        }
    },
    mutations: {
        updateList(state, list) {
            state.list = list;
        },
        updateItemInList(state, newItem) {
            let index = state.list.findIndex(item => item.id === newItem.id)
            if (index !== -1) {
                state.list[index] = newItem;
            }

            let item = state.list.find(item => item.id === newItem.id)
            item.count = newItem.count
        },
        updateCountById(state, newItem) {
            let item = state.list.find(item => item.id === newItem.id)
            item.count = newItem.count
        }
    },
    actions: {
        async getList(context) {
            let res = await axios.get('http://localhost:3000/cartList')
            context.commit('updateList', res.data)
        },
        async patchItemById(context, payload) {
            let res = await axios.patch(`http://localhost:3000/cartList/${payload.id}`, {
                count: payload.count
            })
            // context.commit('updateItemInList',res.data)
            context.commit('updateCountById', res.data)
            console.log('res', res)
        }
    },
    getters: {
        totalCount(state) {
            return state.list.reduce((totalCount, item) => totalCount + item.count, 0)
        },
        totalPrice(state) {
            return state.list.reduce((totalPrice, item, index) => {
                return totalPrice + item.count * item.price
            }, 0)
        },

        selectGoods(state) {
            return state.list.filter(item => item.selected)
        },
        selectGoodsTotalPrice(state, getters) {
            getters.selectGoods.reduce((totalPrice, item) => {
                return totalPrice + item.count * item.price
            }, 0)
        }

    }
}
